import { defineComponent, Component, markRaw, onMounted, ref, toRefs } from 'vue';
import { NCollapse,NTabs,NCard,NTabPane } from 'naive-ui';
import { Element, Connection, Label, Shape } from 'diagram-js/lib/model/Types';
import { Translate } from 'diagram-js/lib/i18n/translate';
import {debounce} from 'lodash-es';

import EventEmitter from '@/components/design/utils/EventEmitter';
import modelerStore from '@/store/modules/modeler';
import editor from '@/store/modules/editor';
import Logger from '@/components/design/utils/Logger';
import { getBusinessObject, type ModdleElement } from 'bpmn-js/lib/util/ModelUtil';
import * as CU from '@/components/design/bo-utils/conditionUtil';
import getBpmnIconType from '@/components/design/bpmn-icons/getIconType';
import bpmnIcons from '@/components/design/bpmn-icons';
import BpmnIcon from '@/components/design/components/common/BpmnIcon.vue';

import { isAsynchronous } from '@/components/design/bo-utils/asynchronousContinuationsUtil';
import { isExecutable } from '@/components/design/bo-utils/executionListenersUtil';
import { isJobExecutable } from '@/components/design/bo-utils/jobExecutionUtil';
import {
  isStartInitializable,
  isUserAssignmentSupported,
} from '@/components/design/bo-utils/initiatorUtil';

import ElementGenerations from './components/ElementGenerations.vue';
import ElementConditional from './components/ElementConditional.vue';
import ExclusiveGateway from '@/components/design/components//Panel/components/ExclusiveGateway.vue';
import ElementDocumentations from './components/ElementDocumentations.vue';
import ElementExecutionListeners from './components/ElementExecutionListeners.vue';
import ElementExtensionProperties from './components/ElementExtensionProperties.vue';
import ElementAsyncContinuations from './components/ElementAsyncContinuations.vue';
import ElementJobExecution from './components/ElementJobExecution.vue';
import ElementStartInitiator from './components/ElementStartInitiator.vue';
/**人员配置 */
import UserAssignment from './components/UserAssignment.vue';


import { isCanbeConditional,isGateway } from '@/components/design/bo-utils/conditionUtil';
import { customTranslate } from '@/components/design/additional-modules/Translate';
import {taskAttr} from '@/store/modules/taskAttr';
import {gateWayAttr} from '@/store/modules/gateWay';
import {createTaskData} from '@/components/design/components/DesignerCommCore/TaskAttr';
import {createGateWayData} from '@/components/design/components/DesignerCommCore/GateWayAttr';
import { connectionAttr } from '@/store/modules/connectionAttr';
import {
  addExecutionListener,
  addEventListener,
  getDefaultEvent,
  getExecutionListeners,
  getExecutionListenerType,
  getExecutionListenerTypes,
  removeExecutionListener,
  updateExecutionListener,
} from '@/components/design/bo-utils/executionListenersUtil';
import {
  addExtensionProperty,
  getExtensionProperties,
  removeExtensionProperty,
} from '@/components/design/bo-utils/extensionPropertiesUtil';
import { message } from 'ant-design-vue';
import {useBpmnStore} from '@/store/modules/bpmnStore';


const Panel = defineComponent({
  name: 'PropertiesPanel',
  props: {
    taskList:{
      type: String as PropType<any>,
      default: undefined,
    },
    connectionList:{
      type: String as PropType<any>,
      default: undefined,
    },
  },

  setup(props) {
    const { taskList,connectionList } = toRefs(props);
    const modeler = modelerStore();
    const panel = ref<HTMLDivElement | null>(null);
    const currentElementId = ref<string | undefined>(undefined);
    const currentElementType = ref<string | undefined>(undefined);
    const taskAttrStore = taskAttr();
    const gateWayStore=gateWayAttr();
    const connecitonAttrStore = connectionAttr();
    const bpmnStore = useBpmnStore();

    const penalTitle = ref<string | undefined>('属性配置');
    const bpmnIconName = ref<string>('Process');
    const bpmnElementName = ref<string>('Process');
    //对象名称：节点名称或流程名称
    const elementName=ref<string>('');
    //点击的是不是流程属性
    const isProcess=ref<boolean>(false);
    const isGateWay=ref<boolean>(false);

    const renderComponents = markRaw<Component[]>([]);

    const setCurrentComponents = (element: BpmnElement) => {
      // 清空
      renderComponents.splice(0, renderComponents.length);
      // renderComponents.push(ElementGenerations);
      // renderComponents.push(ElementDocumentations);
      //renderComponents.push(UserAssignment);

      //方向条件
     // isCanbeConditional(element) && renderComponents.push(ExclusiveGateway);
      
      //网关
      isGateway(element)  && renderComponents.push(ExclusiveGateway);
    
      // isJobExecutable(element) && renderComponents.push(ElementJobExecution);
    
      // isExecutable(element) && renderComponents.push(ElementExecutionListeners);
      // isAsynchronous(element) && renderComponents.push(ElementAsyncContinuations);
      // isStartInitializable(element) && renderComponents.push(ElementStartInitiator);
      console.log(element,"11111111111111")
      if(element.type==="bpmn:EndEvent"||element.type==="bpmn:ServiceTask")
      {
        renderComponents.push(UserAssignment);
      }
      isUserAssignmentSupported(element) && renderComponents.push(UserAssignment);
    };
    console.log(taskList.value,"tasksInfo");
    // 设置选中元素，更新 store
    const setCurrentElement = debounce((element: Shape | Element | Connection | Label | null) => {      
      let activatedElement: BpmnElement | undefined = element;
      let moddleElement: ModdleElement;
      let activatedElementTypeName = '';

      if (!activatedElement) {
        activatedElement =
          modeler.getElRegistry?.find((el) => el.type === 'bpmn:Process') ||
          modeler.getElRegistry?.find((el) => el.type === 'bpmn:Collaboration');

        if (!activatedElement) {
          return Logger.prettyError('No Element found!');
        }
      }
      activatedElementTypeName = getBpmnIconType(activatedElement);

      modeler.setElement(markRaw(activatedElement));
      elementName.value=activatedElement.businessObject.name;
      currentElementId.value = activatedElement.id;
      currentElementType.value = activatedElement.type.split(':')[1];

      penalTitle.value = modeler.getModeler?.get<Translate>('translate')(currentElementType.value);
      bpmnIconName.value = bpmnIcons[activatedElementTypeName];
      bpmnElementName.value = activatedElementTypeName;
      console.log(bpmnElementName.value,"bpmnElementName.value111111");

      //节点数据
      const index = taskAttrStore.tasks.findIndex(item => item.TASK_NODE_NO === activatedElement.id);  
      if (index == -1&&['UserTask','ServiceTask'].includes(bpmnElementName.value)) {
        const blankTask=createTaskData();
        blankTask.TASK_TYPE=activatedElement.businessObject.$attrs["activiti:userTaskType"];
        blankTask.TASK_NODE_NO=activatedElement.id;
        blankTask.TASK_NODE_NAME=activatedElement.name;
        taskAttrStore.addTask(blankTask); 
      }
      if (index == -1&&['ReceiveTask','CallActivity'].includes(bpmnElementName.value)) { 
        const blankTask=createTaskData();
        blankTask.TASK_TYPE="subTask";
        blankTask.TASK_NODE_NO=activatedElement.id;
        blankTask.TASK_NODE_NAME=activatedElement.name;
        taskAttrStore.addTask(blankTask); 
      }
      //网关数据
      const wateWayIndex=gateWayStore.gateWays.findIndex(item => item.GATEWAY_NO === activatedElement.id);
      if (wateWayIndex == -1&&['ParallelGateway','ExclusiveGateway','InclusiveGateway'].includes(bpmnElementName.value)) { 
        console.log(activatedElement,"ParallelGateway11111111111111")
        const blankGateWay=createGateWayData();
        blankGateWay.GATEWAY_TYPE=activatedElement.businessObject.extensionElements.values[0].values[0].$attrs["GatewayType"];
        blankGateWay.GATEWAY_NO=activatedElement.id;
        blankGateWay.GATEWAY_NAME=activatedElement.name;
        gateWayStore.addWateWay(blankGateWay); 
      }
      // console.log(gateWayStore.gateWays,"wateWayStore11111111111111111111111")
      // console.log(activatedElement,"88888888888888888")
      //   console.log(CU.getConditionExpressionValue( activatedElement!),"9999999999999999999999999999999")

      isProcess.value=bpmnElementName.value=="Process" ? false : true;
      
      //isGateWay.value = bpmnElementName.value=="ExclusiveGateway" ? false : true;

      console.log(isProcess.value,"isProcess.value.value111111");
      
      
      
      setCurrentComponents(activatedElement);
      console.log(renderComponents,"renderComponentse111111");
      EventEmitter.emit('element-update', activatedElement);

      // if(isGateway(activatedElement)||isCanbeConditional(activatedElement)){
      //   console.log("jinlaile")
      //   openImportWindow();
      // }
      

      Logger.prettyPrimary(
        'Selected element changed',
        `ID: ${activatedElement.id} , type: ${activatedElement.type}`,
      );
      
    }, 100);

    EventEmitter.on('modeler-init', (modeler) => {
      // 导入完成后默认选中 process 节点
      modeler.on('import.done', () => {
        console.log(1);
        taskAttrStore.setStateData(taskList.value);
        connecitonAttrStore.setStateData(connectionList.value);        
        setCurrentElement(null);
      });
      // 监听选择事件，修改当前激活的元素以及表单
      modeler.on('selection.changed', ({ newSelection }) => {
        console.log(2);
        setCurrentElement(newSelection[0] || null);
      });
      modeler.on('element.changed', ({ element }) => {
        console.log(3);
        const modeling = modelerStore().getModeling;
        const propValue="${"+element.id+"}";
        //节点数据
        const index = taskAttrStore.tasks.findIndex(item => item.TASK_NODE_NO === element.id);  
        if (index == -1&&['bpmn:UserTask','bpmn:ReceiveTask','bpmn:CallActivity'].includes(element.businessObject.$type)) { 
          const blankTask=createTaskData();
          if (index == -1&&['ReceiveTask','CallActivity'].includes(bpmnElementName.value)) { 
            blankTask.TASK_TYPE="subTask";
          }
          else{
            if(element.businessObject.extended!==undefined){
              blankTask.TASK_TYPE=element.businessObject.extended.UserTaskType;
              if(element.businessObject.extended.UserTaskType==="ccTask"){
                blankTask.TASK_RUN_MODE=1;
              }
            }
            else{
              blankTask.TASK_TYPE="userTask";
            } 
          }
          blankTask.TASK_NODE_NO=element.id;
          blankTask.TASK_NODE_NAME=element.name;
          taskAttrStore.addTask(blankTask);
          
          if(element.businessObject.extended!==undefined)
          {
              const newProperty = `${editor().getProcessEngine}:userTaskType`;
              modeling!.updateProperties(element, {
                [newProperty]: propValue === '' ? undefined : element.businessObject.extended.UserTaskType,
              }); 
              if(element.businessObject.extended.UserTaskType==="ccTask"){
                const moddle = modelerStore().getModdle;
                const multiLoopInstance=moddle!.create("bpmn:MultiInstanceLoopCharacteristics",{
                  isSequential: false
                });
                modeling!.updateProperties(element, {
                  loopCharacteristics:multiLoopInstance,
          
                });
                modeling!.updateModdleProperties(element,multiLoopInstance,
                {
                  collection: element.id+"List",
                  elementVariable: element.id
                });
                //设置接收人参数candidateUsers为空
                const exPropKey1 = `${editor().getProcessEngine}:candidateUsers`;
                modeling!.updateProperties(element, {
                  [exPropKey1]: null,
                }); 
                //设置接收人参数assignee
                const propValue="${"+element.id+"}";
                const exPropKey = `${editor().getProcessEngine}:assignee`;
                modeling!.updateProperties(element, {
                  [exPropKey]: propValue === '' ? undefined : propValue,
                }); 
              }
              else{
                const exPropKey = `${editor().getProcessEngine}:candidateUsers`;
                modeling!.updateProperties(element, {
                  [exPropKey]: propValue === '' ? undefined : propValue,
                }); 
              }
          }
          else{
            const exPropKey = `${editor().getProcessEngine}:candidateUsers`;
            modeling!.updateProperties(element, {
              [exPropKey]: propValue === '' ? undefined : propValue,
            }); 
          }
        }
        //网关数据
      const wateWayIndex=gateWayStore.gateWays.findIndex(item => item.GATEWAY_NO === element.id);
      if (wateWayIndex == -1&&['bpmn:ParallelGateway','bpmn:ExclusiveGateway','bpmn:InclusiveGateway'].includes(element.businessObject.$type)) { 
      
        if(element.businessObject.hasOwnProperty("extended"))
          {
            const blankGateWay=createGateWayData();
            blankGateWay.GATEWAY_TYPE=element.businessObject.extended.GatewayType;
            blankGateWay.GATEWAY_NO=element.id;
            blankGateWay.GATEWAY_NAME=element.name;
            gateWayStore.addWateWay(blankGateWay); 
            // const extensionElements = `${editor().getProcessEngine}:GatewayType`;
            // modeling!.updateProperties(element, {
            //   [extensionElements]: propValue === '' ? undefined : element.businessObject.extended.UserTaskType,
            // }); 
            if(element.businessObject.extended!==undefined){
              const extensionElements=getExtensionProperties(element);
              console.log(extensionElements.length,"extensionElements1111")
              if(extensionElements.length==0){
                const newProperty = { GatewayType: element.businessObject.extended.GatewayType };
                addExtensionProperty(element,newProperty);
              }
            }
          }
      }
      let sourceType="bpm";
      if(element.hasOwnProperty("source")){
        if(element.source!=null){
          sourceType=element.source.type;
        }
      }
      //如果存在网关，网关每条出口线路设置表达式
        if(['bpmn:SequenceFlow'].includes(element.businessObject.$type)
          &&['bpmn:ParallelGateway','bpmn:ExclusiveGateway','bpmn:InclusiveGateway'].includes(sourceType)
        &&CU.getConditionExpressionValue(element!)===undefined){
          CU.setConditionExpressionValue(element,`\${${element.id}==true }`); 
        }
        
        //新增节点时，在此处增加taskAttr Pinia
        // 保证 修改 "默认流转路径" 等类似需要修改多个元素的事件发生的时候，更新表单的元素与原选中元素不一致。
        if (element && element.id === currentElementId.value) {
          setCurrentElement(element);
        }
      });
      //点击事件
      modeler.on('element.click', (event) => {
        console.log(4,event);
        console.log(taskAttrStore.tasks,"taskAttrStore.tasks1111");
        //Logger.prettyInfo('Element Click', event);
      });
    });

    onMounted(() => !currentElementId.value && setCurrentElement(null));

    return () => (
      <div ref={panel} class="panel" v-show={isProcess.value&&['StartEvent'].includes(bpmnElementName.value)==false}>
        <div v-show={isProcess.value &&['UserTask','ReceiveTask','CallActivity','ServiceTask','TerminateEndEvent'].includes(bpmnElementName.value)}>
          <div>
          {renderComponents.map((component) => (
            <div><component is={component}></component></div>
          ))}
          </div>
        </div>
        <div v-show={['ExclusiveGateway','ParallelGateway','InclusiveGateway'].includes(bpmnElementName.value)}>
        <div >
          {renderComponents.map((component) => (
            <div >
              <div><component is={component}></component></div>
            </div>
          ))}
          </div>
        </div>
      </div>
     
    );
  },
});

export default Panel;
